# sms_utils.py
from alibabacloud_dypnsapi20170525.client import Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_tea_util import models as util_models
from alibabacloud_dypnsapi20170525.client import Client as Dypnsapi20170525Client
from alibabacloud_dypnsapi20170525 import models as dypnsapi_20170525_models
# 常量 → 后续可挪到 settings.py
AK = 'LTAI5tGG3vybzMMqf5Xqd68y'
SK = 'CeV2X8XVhAi5Pp5Haegkh4KIdgKbqJ'
ENDPOINT = 'dypnsapi.aliyuncs.com'
SCHEME_NAME = '测试方案'          # 控制台复制的方案 Code
SIGN_NAME = '速通互联验证码'     # 已通过审核的签名
TEMPLATE_CODE = '100001'         # 模板 CODE


def get_client():
    config = open_api_models.Config(access_key_id=AK, access_key_secret=SK)
    config.endpoint = ENDPOINT
    return Dypnsapi20170525Client(config)


def send_sms(phone: str, code_len: int = 4, valid_sec: int = 300):
    """
    发验证码
    :param phone: 11 位手机号
    :param code_len: 验证码位数 4~8
    :param valid_sec: 有效期（秒）
    :return: dict  {'success':bool, 'msg':str, 'request_id':str, 'code':str or None}
    """
    client = get_client()
    req = dypnsapi_20170525_models.SendSmsVerifyCodeRequest(
        phone_number=phone,
        country_code='86',
        sign_name='速通互联验证码',
        template_code='100001',
        template_param='{"code":"##code##","min":"5"}',
        scheme_name='测试方案',
        code_length=4,
        valid_time=300,
        duplicate_policy=1,
        interval=60,
        code_type=1,
        return_verify_code=False,
        out_id='',
    )
    runtime = util_models.RuntimeOptions()
    try:
        resp = client.send_sms_verify_code_with_options(req, runtime)
        if resp.body.code == 'OK':
            # print('==========',resp.body.to_map())
            return {'success': True,
                    'msg': '验证码已发送',
                    'request_id': resp.body.request_id,
                    'code': resp.body.model.verify_code}  # 仅调试返回，生产请 False
        else:
            print('6666')
            return {'success': False, 'msg': f"阿里云错误：{resp.body.message}", 'request_id': resp.body.request_id}
    except Exception as e:
        return {'success': False, 'msg': str(e), 'request_id': ''}


def check_sms(phone: str, code: str):
    """
    校验验证码
    :param phone: 11 位手机号
    :param code: 用户输入的验证码
    :return: dict  {'success':bool, 'msg':str}
    """
    client = get_client()
    req = dypnsapi_20170525_models.CheckSmsVerifyCodeRequest(
        phone_number=phone,
        country_code='86',
        verify_code=code,
        scheme_name=SCHEME_NAME
    )
    runtime = util_models.RuntimeOptions()
    try:
        resp = client.check_sms_verify_code_with_options(req, runtime)
        if resp.body.model.verify_result:
            # print('++++++++++++',resp.body.to_map())# ✅ 小写
            return {'success': True, 'msg': '验证通过'}
        else:
            return {'success': False, 'msg': '验证码错误或已过期'}
    except Exception as e:
        return {'success': False, 'msg': str(e)}
